var prevInputText = '';
var searchRes = [];

var el = document.getElementById('app');
var oInput = el.getElementsByClassName('search-inp')[0].getElementsByTagName('input')[0];
var oSearch = el.getElementsByClassName('search')[0];
var oSearchList = el.getElementsByClassName('search-list')[0];

function init () {
  handleInput();
  handleFocus();
  handleClick();
}

function handleInput () {
  oInput.oninput = function (e) {
    var inputText = e.target.value.trim();
    if(inputText === prevInputText) { return };
    getData(inputText, render);
    prevInputText = inputText;
  }
}

function handleFocus () {
  oInput.onfocus = function () {
    if(searchRes.length) {
      oSearchList.style.display = 'block';
    }
  }
}

function handleClick () {
  document.onclick = function (e) {
    var dom = e.target;
    var isSearchFamily = dom === oSearch || oSearch.contains(dom);
  
    if(!isSearchFamily) {
      oSearchList.style.display = 'none';
    }
  }
}



function render (res) {
  searchRes = res;

  if(!res.length) {
    oSearchList.style.display = 'none';
    return;
  }

  var template = '';
  for(var i = 0; i < res.length; i ++) {
    var info = res[i];
    template += `
      <li class="search-info">
        <div class="poster">
          <img src="${info.img}" />
        </div>
        <div class="content">
          <div class="title">
            <span>${info.title}</span>
            ${res.year ? `<span class="year">${res.year}</span>` : ''}
          </div>
          <div class="sub-title">${info.sub_title}</div>
          ${info.episode ? `<div class="episode">共${info.episode}集</div>` : ''}
        </div>
      </li>
    `;
  }
  oSearchList.innerHTML = template;
  oSearchList.style.display = 'block';
}

init();